package com.example.wc.logindemolistview;

import android.content.Context;
import android.util.Log;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.json.JSONObject;

/**
 * Created by hui on 2017/1/13.
 */

public class VolleyRequestDemo {
    private JsonObjectRequest jsonObjectRequest;

    private BlogsLab.Content responseSave;

//    private RequestQueue mQueue;

//    public VolleyRequestDemo(Context context){
//        mQueue = Volley.newRequestQueue(context);
//    }

    public BlogsLab.Content getResponseSave() {
        return responseSave;
    }



    public JsonObjectRequest getJsonObjectRequest() {
        return jsonObjectRequest;
    }

    //    public RequestQueue VolleyRequestQueue(Context context){
//        RequestQueue queue = Volley.newRequestQueue(context);
//        return queue;
//    }

    public interface BlogGetListener{
        public void onBlogGeted(BlogsLab.Content content);
    }
    public void volleyRequestDemo_GET(Context context, final BlogGetListener listener) {

        //此处是主线程，main
        jsonObjectRequest = new JsonObjectRequest("http://www.diyerland.com/diyerland/api/blogs", null,
                //所以子线程可以访问到JsonObject的这个成员变量，在网络成功的时候，由子线程调用
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        //这里是子线程
                        Gson gson = new Gson();
                        responseSave = gson.fromJson(response.toString(), BlogsLab.Content.class);
                        Log.d("TAG", responseSave.toString());
                        //发回通知，数据已经取到
                        if(listener != null){
                            listener.onBlogGeted(responseSave);
                        }
                        //子线程到此结束，运行完成退出
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {

            }
        });
        //这里创建一个子线程，发起网络请求，但是参数是跨线程传递的
        Volley.newRequestQueue(context).add(jsonObjectRequest);
    }


}
